package com.googlecode.lightest.core

class RunnerSupport {
    static final TEMP_DIR = new File(System.getProperty('java.io.tmpdir'))

    public static final OUTPUT_DIR = new File(TEMP_DIR, 'lightest-report')
    public static final RESULTS_XML = 'testng-results.xml'
    public static final FAILED_XML = 'testng-failed.xml'

    def testRunner
    def refreshReport
    def generateHTML

    RunnerSupport() {
        testRunner = new TestRunner()
        refreshReport = false
        generateHTML = false
    }

    void setRefreshReport(boolean refreshReport) {
        this.refreshReport = refreshReport
    }
    
    void setGenerateHTML(boolean generateHTML) {
        this.generateHTML = generateHTML
    }

    /**
     * Runs the suite specified by a resource path, using the given,
     * configuration, and returns the testng-results.xml file.
     *
     * @param suitePath
     * @param configText
     */
    Node runLightest(String suitePath, String configText = "") {
        def suiteStream = this.class.getResourceAsStream(suitePath)
        def suiteFile = createSuiteFileFromStream(suiteStream)

        return runLightest(suiteFile, configText)
    }

    /**
     * Runs the suite specified by a suite XML file, using the given,
     * configuration, and returns the Node representation of the
     * testng-results.xml file. The output directory is always overridden to be
     * OUTPUT_DIR.
     *
     * @param suiteFile
     * @param configText
     */
    Node runLightest(File suiteFile, configText = "") {
        def suites = [ suiteFile.getCanonicalPath() ]

        testRunner.configure(configText)
        testRunner.setOutputDir(OUTPUT_DIR)
        testRunner.setRefreshReport(refreshReport)
        testRunner.setGenerateHTML(generateHTML)
        testRunner.run(suites)

        def resultsFile = new File(testRunner.getOutputDir(), RESULTS_XML)

        return new XmlParser().parse(resultsFile)
    }

    /**
     * Creates and returns a temporary file using the contents of an input
     * stream. The file will be deleted when the JVM exits.
     *
     * @param stream  the stream whose contents to write to the file
     */
    private createSuiteFileFromStream(stream) {
        assert stream != null

        def file = File.createTempFile('lightest-suite', '.xml')
        file.deleteOnExit()
        file.write(stream.text)

        return file
    }
}